<template>
  <!-- 添加子部门弹出提示 -->
  <el-dialog
    :title="this.form.id ? '编辑部门' : '添加部门'"
    :visible="showDialog"
    width="30%"
    @close="cancel"
    :modal-append-to-body="false"
  >
    <!-- 弹出表单 -->
    <el-form
      ref="form"
      :model="form"
      label-width="95px"
      :rules="rules"
      v-loading="loading"
    >
      <!-- 部门名称 -->
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="2-10个字符"
          maxlength="30"
          :show-word-limit="true"
        ></el-input>
      </el-form-item>
      <!-- 部门编码 -->
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          placeholder="2-10个字符"
          maxlength="30"
          :show-word-limit="true"
        ></el-input>
      </el-form-item>
      <!-- 负责人列表 -->
      <el-form-item label="部门负责人" prop="managerId">
        <el-select
          v-model="form.managerId"
          style="width: 100%"
          @focus="getMessagerList"
        >
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          >
          </el-option
        ></el-select>
      </el-form-item>
      <!-- 部门介绍 -->
      <el-form-item label="部门介绍" prop="introduce">
        <!-- :show-word-limit  el语法，是否显示输入字数统计，只在 type = "text" 或 type = "textarea" 时有效-->
        <el-input
          v-model="form.introduce"
          type="textarea"
          placeholder="1-100个字符"
          maxlength="100"
          :show-word-limit="true"
        ></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getDepartmentList,
  getMessagerList,
  addDepartment,
  getDepartmentDetail,
  updataDepartmentDetail,
} from "@/api/department";
export default {
  name: "",
  props: {
    showDialog: Boolean,
  },
  data() {
    // 部门名称自定义校验
    let validateRuleName = async (rule, value, callback) => {
      // 部门名称
      let deptList = await getDepartmentList();
      if (this.form.id)
        deptList = deptList.filter((item) => item.id !== this.form.id);
      const hasRepeat = deptList.some((item) => item.name === value);
      hasRepeat ? callback(new Error("部门名称不能重复")) : callback();
    };
    // 部门编码自定义校验
    let validateRuleCode = async (rule, value, callback) => {
      // 部门名称
      let deptList = await getDepartmentList();
      if (this.form.id)
        deptList = deptList.filter((item) => item.id !== this.form.id);
      const hasRepeat = deptList.some((item) => item.code === value);
      hasRepeat ? callback(new Error("部门编码不能重复")) : callback();
    };
    return {
      form: {
        id: "",
        code: "", // 部门编码
        introduce: "", // 部门介绍
        managerId: "", // 部门负责人名字
        name: "", // 部门名称
        pid: "", // 部门父级部门id
      },
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2-10位字符", trigger: "blur" },
          { validator: validateRuleName, trigger: "blur" },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          { min: 2, max: 10, message: "请输入2-10位字符", trigger: "blur" },
          { validator: validateRuleCode, trigger: "blur" },
        ],
        managerId: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
          // { min: 2, max: 10, message: "请输入2-10位字符", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "请输入2-10位字符", trigger: "blur" },
        ],
      },
      managerList: [], // 负责人列表
      loading: false,
    };
  },
  methods: {
    async getDepartmentDetail(id) {
      this.loading = true;
      // 提前准备好负责人列表数据
      await this.getMessagerList();
      this.form = await getDepartmentDetail(id);
      this.loading = false;
    },
    async getMessagerList() {
      // 调负责人列表接口获取数据，存储数据
      console.log(await getMessagerList());
      this.managerList = await getMessagerList();
    },
    cancel() {
      console.log(this);
      // resetFields()  el语法，对该表单项进行重置，将其值重置为初始值并移除校验结果
      this.$refs.form.resetFields();
      // 关闭弹窗 => 更新弹窗显示隐藏的控制2变量改为false
      this.$emit("update:showDialog", false);
    },
    async confirm() {
      const isOK = await this.$refs.form.validate().catch((err) => err);
      if (!isOK) return;
      // 1.给form增加数据
      if (this.form.id) {
        // 如果存在是编辑部门，调修改接口
        await updataDepartmentDetail(this.form);
      } else {
        // 不存在时添加调添加部门接口
        const { id, ...rest } = this.form;
        await addDepartment(rest);
      }
      // 2. 通知父组件更新数（有新数据录入成功）
      this.$emit("updataDepart");
      // 3. 提示操作成功
      this.$message({
        message: (this.form.id ? "编辑" : "新增") + "部门成功",
        type: "success",
      });
      // 4. 重置表单，关弹窗
      this.cancel();
    },
  },
};
</script>

<style scoped></style>
